home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
- From: Dan Pop <danpop@mail.cern.ch>
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Sun, 21 Jan 1996 21:44:19 +0100
- Organization: CERN European Lab for Particle Physics
- Message-ID: <9601212044.AA18387@dxmint.cern.ch>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dpian$gij@oxy.rust.net> <9601201820.AA01752@dxmint.cern.ch> <TANMOY.96Jan21104404@qcd.lanl.gov>
- X-NNTP-Posting-Host: hpl3sn03.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
- X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
-
- tanmoy@qcd.lanl.gov (Tanmoy Bhattacharya) writes:
-
- >In article <9601201820.AA01752@dxmint.cern.ch> Dan Pop
- ><danpop@mail.cern.ch> writes:
- ><snip>
- > >Given some number, there is a neat trick to generate a mask which will
- > >have exactly one bit set in it. The bit set will be the least
- > >significant non-zero bit in the original number:
- > >
- > > mask = ~number & number;
- > >
- > >Now, if number contained a single non-zero bit (and is therefore a
- > >power of 2), mask will be equal to number. Therefore:
- > >
- > > if (number == (~number & number))
- > > {
- > > /* number is a power of 2 */
- > > }
- > >
- > >Try it, you'll like it!
- >
- > I don't think so. ~number & number will _always_ give 0. -number & number
- > will actually work, except for the case when number == 0. That is,
- > assuming a two's complement implementation. On a one's complement or
- > sign-magnitude implementation it won't work at all.
- >
- >Consider x = 0...0101. -x = 1...1011
- >-x & x == 1. So I cannot quite figure out what was meant above.
-
- And 1 != x, hence x is not a power of 2. QED.
-
- The proponent of the solution explained correctly how it works,
- unfortunately his solution didn't work as explained, so I fixed the
- solution to match the explanations :-)
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-